package com.imooc.bilibili.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imooc.bilibili.domain.UserFollowing;
import com.imooc.bilibili.domain.UserMoments;
import com.imooc.bilibili.service.UserFollowingService;
import com.imooc.bilibili.service.websocket.WebSocketService;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ConfirmConsumer {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserFollowingService userFollowingService;

    @RabbitListener(queues = ConfirmConfig.DANMU_QUEUE_NAME)
    public void danmuConsumer(Message msg){
      log.info("弹幕消费者接收到的消息为：{}",new String(msg.getBody()));
        String bodyStr = new String(msg.getBody());
        JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        String sessionId = jsonObject.getString("sessionId");
        String message = jsonObject.getString("message");
        WebSocketService webSocketService = WebSocketService.WEBSOCKET_MAP.get(sessionId);
        if (webSocketService.getSession().isOpen()) {
            try {
                webSocketService.sendMessage(message);
                log.info("弹幕消费者消费完毕！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RabbitListener(queues = ConfirmConfig.MOMENTS_QUEUE_NAME)
    public void momentsConsumer(Message msgs){
        log.info("动态消费者接收到的消息为：{}",new String(msgs.getBody()));

        String bodyStr = new String(msgs.getBody());
        // 获取消息体中的动态userMoments
        UserMoments userMoments = JSONObject.toJavaObject(JSONObject.parseObject(bodyStr), UserMoments.class);
        Long userId = userMoments.getUserId();
        // 获取发布动态用户的粉丝列表
        List<UserFollowing> fanList = userFollowingService.getUserFans(userId);
        for (UserFollowing fan :  fanList){
            String key = "subscribed-" + fan.getUserId();
            String subscribedListStr = stringRedisTemplate.opsForValue().get(key);
            List<UserMoments> subscribedList = null;
            if (StringUtils.isNullOrEmpty(subscribedListStr)){
                subscribedList = new ArrayList<>();
            }else {
                subscribedList = JSONArray.parseArray(subscribedListStr,UserMoments.class);
            }
            subscribedList.add(userMoments);
            stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(subscribedList));
            log.info("动态消费者已消费完毕消息!");
        }
    }


}
